import React, {useEffect, useState} from 'react';
import {Button, Card, Input, message, Select, Table} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import {useNavigate} from 'react-router-dom';

import LinkButton from '../../components/LinkButton';
import './index.less';
import {reqGetProductList, reqSearchProductList, reqUpdateStatus} from '../../api';
import {PAGE_SIZE} from '../../utils/constants';

/**
 * 二级路由 商品管理
 */
function Product(){
  // navigate跳转路由
  const navigate = useNavigate();
  //存储商品数据列表
  const [productList,setProductList] = useState([]);
  //商品数据总数
  const [total,setTotal] = useState(0);
  //存储搜索商品分页关键字
  const [searchName,setSearchName] = useState("");
  //商品搜索类型
  const [searchType,setSearchType] = useState("productName");
  //第几页
  const [pageNum,setPageNum] = useState(0);

  const columns = [
    {
      title: "商品名称",
      dataIndex: 'name',
    },
    {
      title: "商品描述",
      dataIndex: 'desc',
    },
    {
      title: "价格",
      dataIndex: 'price',
      render: (price)=> {
        return "￥"+price;
      }
    },
    {
      title: "状态",
      width: 100,
      // dataIndex: 'status',
      render: (product)=> {
        const newStatus = product.status===1 ? 2 : 1
        return (
          <span>
            <Button type='primary' onClick={() => updateStatus(product._id, newStatus)}>
              {product.status === 1 ? '下架' : '上架'}
            </Button>
            <span>{product.status === 1 ? '在售' : '已下架'}</span>
          </span>
        )
      }
    },
    {
      title: "操作",
      width: 100,
      render: (product)=>(
        <span>
          <LinkButton onClick={function(){
            navigate('/product/detail',{state: {product: product}});
          }}>详情</LinkButton>
          <LinkButton onClick={function(){
            navigate('/product/update',{state: {product: product}});
          }}>修改</LinkButton>
        </span>
      ),
    },
  ];

  /**
   * 更新指定商品的状态
   * @param productId
   * @param status
   * @returns {Promise<void>}
   */
  async function updateStatus(productId,status){
    const result = await reqUpdateStatus(productId,status)
    if(result.status === 0){
      message.success('更新商品状态成功！');
      await getProductList(pageNum);
    }
  }

  /*
  获取商品数据列表
   */
  async function getProductList(pageNum){
    setPageNum(pageNum);
    let response;
    if(searchName){
      response = await reqSearchProductList(pageNum,PAGE_SIZE,searchName,searchType);
    }else{
      response = await reqGetProductList(pageNum,PAGE_SIZE);
    }

    if(response.status === 0){
      const {total, list} = response.data;
      setTotal(total);
      setProductList(list);
    }else{
      // 获取数据失败！
      message.error("获取数据失败！");
    }
  }

  useEffect(function(){
    getProductList(1).then();
  },[])

  const title = (
    <span>
      <Select value={searchType} style={{width: 130}} onChange={function(value){
        setSearchType(value);
      }}>
        <Select.Option value="productName">按名称搜索</Select.Option>
        <Select.Option value="productDesc">按类型搜索</Select.Option>
      </Select>
      <Input value={searchName} placeholder="关键字" style={{width: 150,margin: '0 10px'}} onChange={function(event){
        setSearchName(event.target.value);
      }}/>
      <Button type="primary" onClick={() => getProductList(1)}>查询</Button>
    </span>
  )


  return (
    <Card
      style={{height: '100%'}}
      title={title}
      extra={<Button onClick={function(){
        navigate('/product/add');
      }} type="primary"><PlusOutlined/> 添加商品</Button>}
    >
      <Table
        dataSource={productList}
        columns={columns}
        pagination={{
          total,defaultPageSize: 4,
          showQuickJumper: true,
          onChange: function(pageNum){
            getProductList(pageNum).then();
          }
        }}
        rowKey="_id"
        bordered
        scroll
      />
    </Card>
  );
}

export default Product;